<template>
  <div class="app-container">
    <div class="document-layout">
      <!-- 左侧元数据区域 -->
      <div class="metadata-panel">
        <div class="panel-header">
          <h2>文档元数据</h2>
        </div> 
        <el-scrollbar class="metadata-scrollbar">
          <el-form :model="documentData" label-position="top" class="metadata-form" size="small">
            <el-form-item label="档号">{{ documentData.dh || '-' }}</el-form-item>
            <el-form-item label="题名">{{ documentData.tm || '-' }}</el-form-item>
            <el-form-item label="主题词">{{ documentData.ztc || '-' }}</el-form-item>
            <el-form-item label="密级">{{ documentData.mj || '-' }}</el-form-item>
            <el-form-item label="保管期限">{{ documentData.bgqx || '-' }}</el-form-item>
            <el-form-item label="分类号">{{ documentData.flh || '-' }}</el-form-item>
            <el-form-item label="案卷号">{{ documentData.ajh || '-' }}</el-form-item>
            <el-form-item label="件号">{{ documentData.jh || '-' }}</el-form-item>
            <el-form-item label="关键词">{{ documentData.gjc || '-' }}</el-form-item>
            <el-form-item label="类别号">{{ documentData.lbh || '-' }}</el-form-item>
            <el-form-item label="文种">{{ documentData.wz || '-' }}</el-form-item>
            <el-form-item label="时间">{{ documentData.sj || '-' }}</el-form-item>
            <el-form-item label="文件编号">{{ documentData.wjbh || '-' }}</el-form-item>
            <el-form-item label="载体类型">{{ documentData.ztlx || '-' }}</el-form-item>
            <el-form-item label="载体数量">{{ documentData.ztsl || '-' }}</el-form-item>
            <el-form-item label="载体单位">{{ documentData.ztdw || '-' }}</el-form-item>
            <el-form-item label="载体规格">{{ documentData.ztgg || '-' }}</el-form-item>
            <el-form-item label="责任者">{{ documentData.zrz || '-' }}</el-form-item>
            <el-form-item label="微缩号">{{ documentData.wsh || '-' }}</el-form-item>
            <el-form-item label="档案管号">{{ documentData.dagh || '-' }}</el-form-item>
            <el-form-item label="数据类型">{{ documentData.sjlx || '-' }}</el-form-item>
            <el-form-item label="附注">{{ documentData.fz || '-' }}</el-form-item>
          </el-form>
        </el-scrollbar>
      </div>

      <!-- 右侧PDF查看区域 -->
      <div class="pdf-panel">
        <div class="panel-header">
          <div class="left-controls">
            <el-radio-group v-model="pdfViewMode" size="small">
              <el-radio-button label="single">单层PDF</el-radio-button>
              <el-radio-button label="double">双层PDF</el-radio-button>
              <el-radio-button label="text">文本</el-radio-button>
            </el-radio-group>
          </div>
        </div>
        
        <div class="pdf-container" :class="pdfViewMode">
          <!-- 单层PDF查看 -->
          <div v-if="pdfViewMode === 'single'" class="pdf-iframe-container">
            <div v-if="pdfUrl" class="iframe-container">
              <embed
                :src="pdfUrl"
                type="application/pdf"
                class="pdf-embed"
                width="100%"
                height="100%"
                alt="PDF文档"
              />
            </div>
            <div v-else class="pdf-placeholder">
              <div class="empty-placeholder">
                <i class="el-icon-document"></i>
                <p>正在加载PDF文件...</p>
              </div>
            </div>
          </div>

          <!-- 双层PDF查看 -->
          <div v-else-if="pdfViewMode === 'double'" class="pdf-iframe-container">
            <div v-if="pdfUrl" class="iframe-container">
              <embed
                :src="pdfUrl"
                type="application/pdf"
                class="pdf-embed"
                width="100%"
                height="100%"
                alt="PDF文档"
              />
            </div>
            <div v-if="loading" class="pdf-loading">
              <div class="el-loading-spinner">
                <i class="el-icon-loading"></i>
                <p class="el-loading-text">加载PDF中...</p>
              </div>
            </div>
            <div v-else-if="!pdfUrl" class="pdf-placeholder">
              <div class="empty-placeholder">
                <i class="el-icon-document"></i>
                <p>正在加载PDF文件...</p>
              </div>
            </div>
          </div>

          <!-- 文本查看 -->
          <div v-else-if="pdfViewMode === 'text'" class="text-container">
            <el-scrollbar class="text-scrollbar">
              <div class="document-paper" v-if="!loading">
              
           
                <div class="document-content" v-if="documentData.content">
                  <pre>{{ documentData.content }}</pre>
                </div>
                <div class="empty-content" v-else>
                  <i class="el-icon-document"></i>
                  <p>暂无文档内容</p>
                  <el-button size="small" type="primary" @click="pdfViewMode = 'single'">查看PDF</el-button>
                </div>
              </div>
              <div class="loading-placeholder" v-else>
                <div class="el-loading-spinner">
                  <i class="el-icon-loading"></i>
                  <p class="el-loading-text">正在加载中...</p>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- PDF加载中或错误状态 -->
          <div v-if="loading && !pdfLoadError" class="pdf-overlay loading">
            <el-progress 
              v-if="loadingStatus === 'success'" 
              type="circle" 
              :percentage="loadingProgress" 
              status="success">
            </el-progress>
            <el-progress 
              v-else-if="loadingStatus === 'exception'" 
              type="circle" 
              :percentage="loadingProgress" 
              status="exception">
            </el-progress>
            <el-progress 
              v-else 
              type="circle" 
              :percentage="loadingProgress">
            </el-progress>
          </div>
          <div v-if="pdfLoadError" class="pdf-overlay error">
            <div class="error-result">
              <i class="el-icon-error"></i>
              <h3>PDF加载失败</h3>
              <p>{{ errorMessage }}</p>
              <el-button type="primary" @click="retryLoading">重试</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ocrArtApi } from '@/api/ocrart'

export default {
  name: 'DocumentShow',
  components: {
    // 不再需要 pdf 组件
    // 'pdf': pdf
  },
  data() {
    return {
      // 文档数据
      documentData: {
        wjbh: '', // 文件编号
        dh: '', // 档号
        bgqx: '', // 保管期限
        lbh: '', // 类别号
        ajh: '', // 案卷号
        jh: '', // 件号
        zrz: '', // 责任者
        ztsl: '', // 载体数量
        ztdw: '', // 载体单位
        ztgg: '', // 载体规格
        flh: '', // 分类号
        ztc: '', // 主题词
        fz: '', // 附注
        content: '', // 文档文本内容
        bt: '', // 题名
        fwjg: '', // 发文机关
        fwrq: '', // 发文日期
        mj: '', // 密级
        gjc: '', // 关键词
        wz: '', // 文种
        sj: '', // 时间
        wsh: '', // 微缩号
        dagh: '', // 档案管号
        sjlx: '', // 数据类型
        ztlx: '' // 载体类型
      },
      
      // PDF查看相关
      pdfViewMode: 'single', // 默认使用单层PDF
      pdfUrl: '', // 原始PDF文件URL
      
      // 加载状态
      loading: false,
      loadingProgress: 0,
      loadingStatus: '',
      pdfLoadError: false,
      errorMessage: ''
    }
  },
  
  computed: {
    documentId() {
      return this.$route.query.id
    }
  },
  
  created() {
    // 获取文档数据
    this.fetchDocumentData()
  },
  
  mounted() {
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize)
    console.log('组件已挂载，添加事件监听器');
  },
  
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.handleResize)
    
    console.log('组件将销毁，已清理资源');
  },
  
  watch: {
    pdfViewMode(newMode, oldMode) {
      // 如果模式发生变化，重新获取文档数据
      if (newMode !== oldMode && this.documentId) {
        console.log(`视图模式从 ${oldMode} 切换到 ${newMode}`);
        
        // 重新获取文档数据
        this.fetchDocumentData();
      }
    }
  },
  
  methods: {
    // 获取文档数据
    async fetchDocumentData() {
      if (!this.documentId) return
      
      this.loading = true
      this.loadingStatus = ''
      this.loadingProgress = 30
      try {
        const response = await ocrArtApi('getDocById', { id: this.documentId })
        if (response.code === 200 && response.data) {
          console.log('获取文档数据成功:', response.data);
          this.documentData.dh = response.data.dh;
          this.documentData.tm = response.data.tm;
          this.documentData.ztc = response.data.ztc;
          this.documentData.mj = response.data.mj;
          this.documentData.bgqx = response.data.bgqx;
          this.documentData.flh = response.data.flh;
          this.documentData.ajh = response.data.ajh;
          this.documentData.jh = response.data.jh;
          this.documentData.gjc = response.data.gjc;
          this.documentData.lbh = response.data.lbh;
          this.documentData.wz = response.data.wz;
          this.documentData.sj = response.data.sj;
          this.documentData.wjbh = response.data.wjbh;
          this.documentData.ztlx = response.data.ztlx;
          this.documentData.ztsl = response.data.ztsl;
          this.documentData.ztdw = response.data.ztdw;  
          this.documentData.ztgg = response.data.ztgg;
          this.documentData.zrz = response.data.zrz;
          this.documentData.wsh = response.data.wsh;
          this.documentData.dagh = response.data.dagh;
          this.documentData.sjlx = response.data.sjlx;
          this.documentData.fz = response.data.fz;
          
          
          // 如果是文本模式，则无需加载PDF
          if (this.pdfViewMode === 'text') {
            console.log('文本模式，显示文本内容');
            // 如果API响应中没有content字段，可以尝试从其他字段获取
            if (!this.documentData.content && response.data.content) {
              this.documentData.content = response.data.content;
            }
            this.loading = false;
            return;
          }
          
          // 获取PDF文件URL
          if (response.data.file_path) {
            this.pdfUrl = this.getPdfUrl(response.data.file_path)
            this.loadingProgress = 60;
          } else if (response.data.single_layer_pdf || response.data.double_layer_pdf) {
            console.log('找到PDF URL:', {
              单层: response.data.single_layer_pdf,
              双层: response.data.double_layer_pdf,
              当前模式: this.pdfViewMode
            });
            
            // 根据当前视图模式选择合适的PDF
            let pdfUrl;
            if (this.pdfViewMode === 'single') {
              // 单层模式优先使用单层PDF
              pdfUrl = response.data.single_layer_pdf || response.data.double_layer_pdf;
              console.log('单层模式使用PDF:', pdfUrl);
            } else {
              // 双层模式优先使用双层PDF
              pdfUrl = response.data.double_layer_pdf || response.data.single_layer_pdf;
              console.log('双层模式使用PDF:', pdfUrl);
            }
            
            if (pdfUrl) {
              console.log(`使用${this.pdfViewMode === 'single' ? '单层' : '双层'}PDF URL:`, pdfUrl);
              this.pdfUrl = pdfUrl;
              this.loadingProgress = 60;
            } else {
              console.error('未找到可用的PDF文件');
              throw new Error('未找到PDF文件');
            }
          } else {
            throw new Error('文档路径不存在')
          }
          
          // 设置加载完成
          this.loadingProgress = 100;
          this.loadingStatus = 'success';
          this.loading = false;
          
        } else {
          throw new Error(response.message || '获取文档数据失败')
        }
      } catch (error) {
        console.error('获取文档数据出错:', error)
        this.pdfLoadError = true
        this.errorMessage = error.message || '获取文档数据失败'
        this.loadingStatus = 'exception'
        this.loading = false
      }
    },
    
    // 构建PDF URL
    getPdfUrl(filePath) {
      // 根据实际情况构建PDF访问URL
      return `/api/admin/ProcessDocument/getFile?path=${encodeURIComponent(filePath)}`
    },
    
    // 重试加载
    retryLoading() {
      this.pdfLoadError = false
      this.loading = true
      this.loadingProgress = 0
      this.loadingStatus = ''
      this.fetchDocumentData()
    },
    
    // 处理窗口大小变化
    handleResize() {
      // 窗口大小变化时的处理逻辑
    },
    
    // 复制选中的文本
    copySelectedText() {
      try {
        // 使用浏览器自带的复制功能，无需特殊处理
        // embed 标签中的文本选择会自动被浏览器处理
        document.execCommand('copy');
        this.$message.success('文本已复制');
      } catch (error) {
        console.error('复制文本出错:', error);
        this.$message.error('复制失败: ' + error.message);
      }
    },
    
    // 处理双层PDF iframe加载完成事件，已不需要
    onDoublePdfIframeLoaded(event) {
      // 使用embed标签不再需要此方法
    },
    
    // 修正中文文本的阅读顺序，已不需要
    correctChineseTextOrder(text) {
      // 使用embed标签不再需要此方法
      return text;
    },
    
    // 测试文本反转，已不需要
    testTextReversal() {
      // 使用embed标签不再需要此方法
    },
    
    // 注入自定义样式到iframe中，只隐藏搜索相关的元素
    injectCustomStyles(event) {
      // 使用embed标签不再需要此方法
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: calc(100vh - 84px);
  overflow: hidden;
}

.document-layout {
  display: flex;
  height: 100%;
  gap: 20px;
}

// 左侧元数据面板
.metadata-panel {
  width: 320px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.panel-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  
  h2 {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin: 0;
  }
}

.metadata-scrollbar {
  flex: 1;
  height: 0;
}

.metadata-form {
  padding: 15px;
  
  ::v-deep .el-form-item {
    margin-bottom: 12px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: #c0c4cc;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    }
    
    .el-form-item__label {
      background-color: #f5f7fa;
      padding: 8px 12px;
      border-bottom: 1px solid #ebeef5;
      display: block;
      width: 100%;
      text-align: left;
      font-weight: 500;
      font-size: 13px;
      color: #606266;
      transition: background-color 0.3s ease;
    }
    
    .el-form-item__content {
      padding: 8px 12px;
      font-size: 13px;
      color: #606266;
      word-break: break-all;
      min-height: 36px;
      display: flex;
      align-items: center;
      
      &:empty::before {
        content: '-';
        color: #c0c4cc;
      }
    }
    
    &:hover .el-form-item__label {
      background-color: #eef1f6;
    }
  }
}

// 右侧PDF面板
.pdf-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pdf-panel .panel-header {
  padding: 10px 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-controls {
  display: flex;
  align-items: center;
}

.zoom-controls {
  margin: 0 10px;
}

.page-info, .scale-info {
  min-width: 70px;
}

// PDF容器
.pdf-container {
  flex: 1;
  position: relative;
  overflow: hidden;
  background-color: #f5f5f5;
}

// PDF iframe容器
.pdf-iframe-container {
  width: 100%;
  height: 100%;
}

.iframe-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

// 加载和错误状态
.pdf-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 100;
}

.pdf-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.empty-placeholder {
  text-align: center;
  padding: 20px;
  i {
    font-size: 48px;
    color: #909399;
    margin-bottom: 10px;
  }
  p {
    font-size: 14px;
    color: #909399;
  }
}

.error-result {
  text-align: center;
  padding: 20px;
  i {
    font-size: 48px;
    color: #f56c6c;
    margin-bottom: 10px;
  }
  h3 {
    font-size: 16px;
    color: #606266;
    margin: 0;
  }
  p {
    font-size: 14px;
    color: #909399;
  }
}

/* 文本查看样式 */
.text-container {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  overflow: hidden;
}

.text-scrollbar {
  height: 100%;
  padding: 30px;
}

.document-paper {
  position: relative;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 40px;
  margin: 0 auto;
  max-width: 900px;
  min-height: calc(100% - 60px);
  color: #303133;
  font-size: 15px;
  line-height: 1.8;
  word-break: break-all;
  transition: all 0.3s ease;
  animation: fadeIn 0.5s ease-in-out;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 6px;
    background: linear-gradient(to right, #4e7ccc, #3a8ee6, #67c23a);
    border-radius: 8px 8px 0 0;
  }
}

.document-title {
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 30px;
  line-height: 1.5;
  color: #303133;
}

.document-metadata {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
  border-left: 4px solid #3a8ee6;
}

.metadata-item {
  margin-right: 20px;
  margin-bottom: 10px;
  font-size: 14px;
  
  .label {
    color: #606266;
    margin-right: 4px;
    font-weight: 500;
  }
  
  .value {
    color: #303133;
  }
}

.document-content {
  border-top: 1px dashed #dcdfe6;
  padding-top: 20px;
  
  pre {
    margin: 0;
    font-family: "Microsoft YaHei", Arial, sans-serif;
    white-space: pre-wrap;
    font-size: 15px;
    line-height: 1.8;
  }
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  
  i {
    font-size: 60px;
    color: #dcdfe6;
    margin-bottom: 20px;
  }
  
  p {
    font-size: 16px;
    color: #909399;
    margin-bottom: 20px;
  }
}

.loading-placeholder {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 40px;
  margin: 0 auto;
  max-width: 900px;
  min-height: calc(100% - 60px);
}

// 响应式样式
@media (max-width: 1200px) {
  .document-layout {
    flex-direction: column;
  }
  
  .metadata-panel {
    width: 100%;
    height: 30%;
    min-height: 200px;
  }
  
  .pdf-panel {
    height: 70%;
  }
}

/* 在单层PDF模式下隐藏工具栏和搜索相关元素 */
.single .pdf-iframe {
  :deep(#toolbarContainer),
  :deep(#findbar),
  :deep(#secondaryToolbar),
  :deep(.findbar),
  :deep(.toolbar),
  :deep(.toolbarButton),
  :deep(#toolbarViewFind),
  :deep(#findbarOptionsOneContainer),
  :deep(#findbarOptionsTwoContainer),
  :deep(#findInputAutoComplete),
  :deep(#findMsg),
  :deep(button[data-l10n-id="find_previous"]),
  :deep(button[data-l10n-id="find_next"]),
  :deep(.findbar .toolbarField),
  :deep(.textLayer) {
    display: none !important;
    pointer-events: none !important;
    visibility: hidden !important;
  }
}

/* 确保iframe内容可以全屏显示 */
.pdf-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 不再需要的样式 */
.vue-pdf-container,
.vue-pdf,
.pdf-controls {
  display: none;
}

.pdf-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 20;
}

.el-loading-spinner {
  text-align: center;
  
  i.el-icon-loading {
    font-size: 32px;
    color: #409EFF;
  }
  
  .el-loading-text {
    margin-top: 10px;
    font-size: 14px;
    color: #606266;
  }
}

.test-toolbar {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 30;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 4px;
  padding: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pdf-embed {
  width: 100%;
  height: 100%;
  border: none;
  background-color: #f5f7fa;
}
</style>
